package simpleim

import (
	"context"
	"encoding/json"
	"github.com/IBM/sarama"
	"log"
	"strconv"
)

type IMService struct {
	p sarama.SyncProducer
}

func (im *IMService) Produce(ctx context.Context, sender int64, msg Message) error {
	// 转发到 Kafka 里面，以通知别的网关节点
	// 1. 查找目标
	members := im.findMembers()
	for _, member := range members {
		if member == sender {
			continue
		}
		msgJson, err := json.Marshal(MsgEvent{Receiver: member, Msg: msg})
		if err != nil {
			continue
		}
		_, _, err = im.p.SendMessage(&sarama.ProducerMessage{
			Topic: topic,
			Key:   sarama.ByteEncoder(strconv.FormatInt(member, 10)),
			Value: sarama.ByteEncoder(msgJson),
		})
		if err != nil {
			log.Println("发送消息失败", err)
			continue
		}
	}
	return nil
}
func (im *IMService) findMembers() []int64 {
	return []int64{1, 2, 3, 4}
}
